/* 当数据的某个字段其中有空值，返回-- */
export function isNull(val) {
    return (val == "" || val == undefined || val == null) ? " — " : val;
};

/* 当数据的某个字段其中有空值，返回true */
export function isNullTrue(val) {
    return (val == "" || val == undefined || val == null) ? true : false;
};

/* 截取出生日期长度，显示年月日 */
export function isBirthDate(val) {
    return isNotNull(val) ? "" : val.substring(0, 10);
};

/* 计算两个数据 val(除数)，dividends（被除数）*/
export function isCalculate(val, dividends, dividends2) {

    if(isNotNull(val) || isNotNull(dividends) || isNotNull(dividends2)){
        return " - ";
    }else{
        return val/dividends/dividends2 ;
    }
};

function isNotNull(val) {
    return (val == "" || val == undefined || val == null) ? true : false;
};


//美分变美元，人民币同
export function centToDollar(cent) {
    if (cent) {
        var dollar = cent / 100;
        return parseFloat(dollar.toFixed(2));
    }
    return 0;
}


//除以100
export function dividedBy100(cent) {
    if (cent) {
        return cent / 100;
    }
    return 0;
}
//汇率
export function computeRate(rate) {
    if (rate) {
        return rate / 10000;
    }
    return 0;
}
//去除前后空格
export function trimBlank(rate) {
    return rate.replace(/(^\s*)|(\s*$)/g, "");
}


//除法函数，用来得到精确的除法结果
//说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
//调用：accDiv(arg1,arg2)
//返回值：arg1除以arg2的精确结果
export function accDiv(arg1,arg2){
    var t1=0,t2=0,r1,r2;
    try{t1=arg1.toString().split(".")[1].length}catch(e){}
    try{t2=arg2.toString().split(".")[1].length}catch(e){}
    r1=Number(arg1.toString().replace(".",""));
    r2=Number(arg2.toString().replace(".",""));
    return (r1/r2)*Math.pow(10,t2-t1);
}
//乘法函数，用来得到精确的乘法结果
//说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
//调用：accMul(arg1,arg2)
//返回值：arg1乘以arg2的精确结果
export function accMul(arg1,arg2)
{
    var m=0,s1=arg1.toString(),s2=arg2.toString();
    try{m+=s1.split(".")[1].length}catch(e){}
    try{m+=s2.split(".")[1].length}catch(e){}
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
}
//加法函数，用来得到精确的加法结果
//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
//调用：accAdd(arg1,arg2)
//返回值：arg1加上arg2的精确结果
export function accAdd(arg1,arg2){
    var r1,r2,m;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    return (arg1*m+arg2*m)/m;
}
//减法函数 arg2-arg1
export function accSub(arg1,arg2){
    var r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    //last modify by deeka
    //动态控制精度长度
    n=(r1>=r2)?r1:r2;
    return ((arg2*m-arg1*m)/m).toFixed(n);
}


//截取json并拼接新的json 公司 部门 组织
export function getnewjson(json)
{
    if(json == null || json == undefined || json == '') {
        return null;
    }
    var obj = [];
    for(var i = 0,len=json.length; i < len; i++){
        let company = json[i].children;
        if(company == null || company == undefined || company == '') {
            continue;
        }
        for(var j = 0; j < company.length; j++) {

            var customer = {};
            customer.children = company[j].children;
            customer.company_id= company[j].company_id;
            customer.department_name= company[j].department_name;
            customer.department_no= company[j].department_no;
            customer.id = company[j].id;
            customer.level = company[j].level;
            customer.remark = company[j].remark;
            customer.sort_no = company[j].sort_no;
            customer.state = company[j].state;

            obj.push(customer);
        }
    }

    return obj;
}


/* 从右往左每3位数字加一个逗号的js
 *  其中正负数，小数等
  * */
export function formatNum(num) {
    var num = (num || 0).toString(), result = '', str = '', t = '';
    if(num.indexOf('.') != -1){
        str = '.' + num.toString().split('.')[1];
        num = parseInt(num).toString();
    }

    if(num.indexOf('-') != -1 || num.indexOf('+') != -1){
        t = num.substring(0,1);
        num = num.substring(1);
    }
    while (num.length > 3) {
        result = ',' + num.slice(-3) + result;
        num = num.slice(0, num.length - 3);
    }
    if (num) { result = num + result; }
    return t + result + str;
}


/**=========================================== 检查项 ================================================= */
/**
 * js比较两个数组对象,取出不同的值
 *  oldArray 对象数组，result 对象，array2 要遍历的数组，flag 是否找到
 *  返回 oldArray
 */
export function treeTableRefresh(result, array2, flag) {

    for(var i = 0; i < array2.length; i++){
        if(result.ttype == 2 && array2[i].id == result.id){         //update
            let temp_dirver = array2[i];
            temp_dirver.item_name = result.item_name;
            temp_dirver.item_order_number = result.item_order_number !== undefined ? result.item_order_number : temp_dirver.item_order_number;
            temp_dirver.star_level = result.star_level !== undefined ? result.star_level : temp_dirver.star_level;
            temp_dirver.item_main_point = result.item_main_point !== undefined ? result.item_main_point : temp_dirver.item_main_point;
            array2[i] == temp_dirver;
            flag = true;
            break;

        /*}else if(result.ttype == 1 && result.item_level === '1'){                     //add 一级
            result["_expanded"] = true;
            result["_expanded2"] = false;
            if(array2[0].id !== result.id){array2.unshift(result);} break;*/

        }else if(result.ttype == 1 && array2[i].id == result.item_parentid){          //add 二三级

            result["_expanded2"] = true;

            if(isNotNull(array2[i].child_dto_list)){                      //add 二级（从无到有）

                result["_expanded"] = true;
                array2[i].child_dto_list = new Array();
                array2[i].child_dto_list.splice(0,0,result);
                array2[i]["_expanded2"] = result.item_level == 3 ? true : false;

            }else if(array2[i].child_dto_list[array2[i].child_dto_list.length - 1].id !== result.id){      //add 二级 保持一致
                result["_expanded"] = array2[i].child_dto_list[0]["_expanded"];
                // array2[i].child_dto_list.unshift(result);
                array2[i].child_dto_list.push(result);
                array2[i]["_expanded2"] = result.item_level == 3 ? true : false;
            }

            break;

        } else if(result.ttype == 3 && array2[i].id == result.id){         //delete
            array2.splice(i,1);
            if(array2.length == 0){array2 = null;}break;

        } else if(result.ttype == 4 && array2[i].id == result.before_id){         //sort
            array2[i]["item_order"] = result.after;
            array2[i+1]["item_order"] = result.before;
            array2[i] = array2.splice((i+1), 1, array2[i])[0];
            break;

        }  else if(!flag && !isNotNull(array2[i].child_dto_list)){
            treeTableRefresh(result, array2[i].child_dto_list, flag);
        }
    }
}

/**
 * 将一维的扁平数组转换为多层级数组
 */
export function buildTree(data){
    data.forEach(ele => {
        let parentId = ele.item_parentid;
        if (parentId === '0') {
            //是根元素的hua ,不做任何操作,如果是正常的for-i循环,可以直接continue.
        } else {
            //如果ele是子元素的话 ,把ele扔到他的父亲的child数组中.
            data.forEach(d => {
                if (d.id === parentId) {
                    let childArray = d.child_dto_list;
                    if (!childArray) {
                        childArray = []
                    }
                    childArray.push(ele);
                    d.child_dto_list = childArray;
                }
            })
        }
    });
    //去除重复元素
    data = data.filter(ele => {if(ele.item_parentid === '0') {return ele;}});
    return data;
}


/**
 * 下载文件
 */
export function saveAs(fileurl, filename) {
    if(fileurl.indexOf(".docx") > -1 || fileurl.indexOf(".doc") > -1 || fileurl.indexOf(".xlsx") > -1) {
        let elemIF = document.createElement('iframe');
        elemIF.src = fileurl;
        elemIF.style.display = 'none';
        document.body.appendChild(elemIF);
    } else {
        window.open(fileurl)
    }
}

export function debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result
    const later = function() {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp

        // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
            if (!immediate) {
                result = func.apply(context, args)
                if (!timeout) context = args = null
            }
        }
    }

    return function(...args) {
        context = this
        timestamp = +new Date()
        const callNow = immediate && !timeout
        // 如果延时不存在，重新设定延时
        if (!timeout) timeout = setTimeout(later, wait)
        if (callNow) {
            result = func.apply(context, args)
            context = args = null
        }

        return result
    }
}